<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use Hash;

class UserController extends Controller
{
    /**
     * 列表显示
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //读取用户的信息
        $users = User::paginate(10);// User  =====  DB::table('users');

        return view('admin.user.index',['users'=>$users]);

    }

    /**
     * 显示页面添加的表单
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('admin.user.create');
    }

    /**
     * 存储用户
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
        'username' => 'required|regex:/\w{8,18}/',
        'password' => 'required|regex:/\S{6,30}/'
        ],[
            'username.required' => '用户名不能为空',
            'username.regex' => '用户名格式不正确',
            'password.required' => '密码不能为空',
            'password.regex' => '密码格式不正确'
        ]);

        //实例化模型对象
        $user = new User;

        $user->username = $request->username;
        $user->password = Hash::make($request->password);
        $user->email = $request->email;
        $user->chengwei = $request->chengwei;

        // dd($request->all());
        $user->save();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //读取用户的信息
        $user = User::findOrFail($id);

        //显示模板
        return view('admin.user.edit',['user'=>$user]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //表单验证


        //读取内容
        $user = User::findOrFail($id);

        //提取内容
        $user->username = $request->username;
        $user->email = $request->email;
        $user->chengwei = $request->chengwei;

        // dd($request->all());
        $user->save();
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //获取数据
        $user = User::findOrFail($id);

       

        if($user->delete()){
            return back()->with('success','执行成功');
        }else{
            return back()->with('error','执行失败');
        }
    }
}
